#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <queue>
#include <vector>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Node {
   public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
    Node* p;
    void midOrder(Node* root) {
        if (root) {
            midOrder(root->left);
            if (p) {
                p->right = root;
                root->left = p;
            }
            p = root;
            midOrder(root->right);
        }
    }

   public:
    Node* treeToDoublyList(Node* root) {
        if (!root)
            return root;
        Node* head = root;
        while (head->left) {
            head = head->left;
        }
        midOrder(root);
        p->right = head;
        head->left = p;
        return head;
    }
};

int main() {
    Node* root = new Node(4);
    root->left = new Node(2);
    root->right = new Node(5);
    root->left->left = new Node(1);
    root->left->right = new Node(3);
    Solution().treeToDoublyList(root);
    return 0;
}
